package com.doubleview.demo

/**
 * @author huchengchao@kuaishou.com
 * Created on 2021-11-20
 */
//==========================闭包执行上下文与闭包委托==========================
class _Example_ {
    def out = {
        // 这是相对而言的内部闭包。
        def inner = {}
        //------test of thisObject, owner, delegate----------//
        println out.thisObject.getClass().name        //_Example_
        println out.owner.getClass().name            //_Example_
        println out.delegate.getClass().name        //_Example_

        println inner.thisObject.getClass().name    //_Example_
        println inner.thisObject.hashCode()         // == out.thisObject.hashCode
        println inner.owner.getClass().name         //_Example_$_closure1 (指外部闭包被编译的内部类)
        println inner.delegate.getClass().name      //_Example_$_closure1 (指外部闭包被编译的内部类)
    }
}

new _Example_().out()

//=======================如果一个闭包内部使用的方法或变量在局部块内没有，那么 Groovy 优先在 thisObject 或者 owner 域查找；否则，试图从 delegate 那里查找=======================
class _Proxy_ {
    def func1 = { println "this [func1] is from the instance of Class: _Proxy_" }
    def func2 = { println "this [func2] is still from the instance of Class: _Proxy_" }
}

class _Example_2 {

    def func1 = { println "this [func1] is from the instance of Class:_Example_." }
    def out = {
        def func2 = { println "this [func2] is from the instance of closure:out" }
        def inner = {
            func1()
            func2()
        }
        inner.delegate = new _Proxy_()
        inner()
    }
}

new _Example_2().out()


//======================= Groovy 倒置查找顺序,, 即优先选择 delegate 的方法，其次才是 owner 或 this =======================
class _Example_3 {
    def func1 = { println "this [func1] is from the instance of Class: _Example_" }
    def func2 = { println "this [func2] is still from the instance of Class: _Example_" }
    def out = {
        def inner = {
            func1()
            func2()
        }
        new _Proxy_().with inner
    }
}

//this [func1] is from the instance of Class: _Proxy_
//this [func2] is still from the instance of Class: _Proxy_
new _Example_3().out()
